﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Xml.Linq;
using System.IO;
using System.Net;

namespace VCommons
{
    public class CreateFile
    {
        #region 根据请求的页面生成文件，用来生成静态文件


        /// <summary>
        /// 根据请求的页面生成文件，用来生成静态文件
        /// </summary>
        /// <param name="rewriteUrl">请求路径，绝对网络路径</param>
        /// <param name="rewriteFileName">生成文件名称,相对路径</param>
        /// <returns>true：成功，false：失败</returns>
        public static bool CreateStaticFileAuto(string rewriteUrl, string rewriteFileName)
        {
            string logs = string.Empty;
            try
            {
                //获取请求结果
                if ((!string.IsNullOrEmpty(rewriteUrl)) && (!string.IsNullOrEmpty(rewriteFileName)))
                {
                    CookieContainer cookies = new CookieContainer();

                    HttpWebRequest wReq = HttpWebRequest.Create(rewriteUrl) as HttpWebRequest;                
                    HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse;
                    System.IO.Stream respStream = wResp.GetResponseStream();
                    System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.UTF8);
                    string text = reader.ReadToEnd();               
                    respStream.Dispose();
                    reader.Dispose();
                    //生成文件路径
                    string filePath = System.AppDomain.CurrentDomain.BaseDirectory + rewriteFileName;
                    //生成文件目录
                    string dir = filePath.Substring(0, filePath.LastIndexOf("\\"));
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    using (System.IO.StreamWriter srFile = new System.IO.StreamWriter(filePath, false))
                    {
                        text += "<!--生成时间：" + DateTime.Now + "-->";
                        srFile.WriteLine(text);
                        srFile.Close();
                        srFile.Dispose();
                        return true;
                    }
                }
                logs = DateTime.Now + "\r\n事件名称：生成静态页写文件函数\r\n结果:\r\n生成失败，错误信息为：请求路径或生成文件名称为空\r\n请求路径为：" + rewriteUrl + "\r\n生成文件名称为：" + rewriteFileName + "\r\n";
                logs.AddLogFiles("/Logs/CreateFile/" + DateTime.Now.FormatDateToString("yyyyMMdd") + ".log", 1);
                return false;
            }
            catch (Exception ex)
            {
                logs = DateTime.Now + "\r\n事件名称：生成静态页写文件函数\r\n结果:\r\n生成失败，异常信息为：\r\n" + ex.ToString();
                logs.AddLogFiles("/Logs/CreateFile/" + DateTime.Now.FormatDateToString("yyyyMMdd") + ".log", 1);
                return false;
            }

        }



        /// <summary>
        /// 读取post过来的数据
        /// </summary>
        /// <returns></returns>
        public static string PostInput()
        {
            try
            {
                System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
                int count = 0;
                byte[] buffer = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, 1024)) > 0)
                {
                    builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                return builder.ToString();
            }
            catch (Exception ex)
            { throw ex; }
        }



        /// <summary>
        /// 获取post参数
        /// </summary>
        /// <returns></returns>
        public static SortedList Param()
        {
            string POSTStr = PostInput();
            SortedList SortList = new SortedList();
            int index = POSTStr.IndexOf("&");
            string[] Arr = { };
            if (index != -1) //参数传递不只一项
            {
                Arr = POSTStr.Split('&');
                for (int i = 0; i < Arr.Length; i++)
                {
                    int equalindex = Arr[i].IndexOf('=');
                    string paramN = Arr[i].Substring(0, equalindex);
                    string paramV = Arr[i].Substring(equalindex + 1);
                    if (!SortList.ContainsKey(paramN)) //避免用户传递相同参数
                    { SortList.Add(paramN, paramV); }
                    else //如果有相同的，一直删除取最后一个值为准
                    { SortList.Remove(paramN); SortList.Add(paramN, paramV); }
                }
            }
            else //参数少于或等于1项
            {
                int equalindex = POSTStr.IndexOf('=');
                if (equalindex != -1)
                { //参数是1项
                    string paramN = POSTStr.Substring(0, equalindex);
                    string paramV = POSTStr.Substring(equalindex + 1);
                    SortList.Add(paramN, paramV);

                }
                else //没有传递参数过来
                { SortList = null; }
            }
            return SortList;
        }
        #endregion


        public static bool CreateStaticFileAuto(string rewriteUrl, string rewriteFileName, string userRole)
        {

            string logs = string.Empty;
            try
            {
                //获取请求结果
                if ((!string.IsNullOrEmpty(rewriteUrl)) && (!string.IsNullOrEmpty(rewriteFileName)))
                {
                    CookieContainer cookies = new CookieContainer();

                    HttpWebRequest wReq = HttpWebRequest.Create(rewriteUrl) as HttpWebRequest;
                    Cookie cookie = new Cookie("xxb_WebUserRole", userRole);
                    cookie.Domain = "eee114.com";
                    cookie.Expires = DateTime.Now.AddMinutes(2);
                    cookies.Add(cookie);
                    wReq.CookieContainer = cookies; 
                    HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse;

                    System.IO.Stream respStream = wResp.GetResponseStream();
                    System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.UTF8);
                    string text = reader.ReadToEnd();

                    respStream.Dispose();
                    reader.Dispose();
                    //生成文件路径
                    string filePath = System.AppDomain.CurrentDomain.BaseDirectory + rewriteFileName;
                    //生成文件目录
                    string dir = filePath.Substring(0, filePath.LastIndexOf("\\"));
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    using (System.IO.StreamWriter srFile = new System.IO.StreamWriter(filePath, false))
                    {
                        text += "<!--生成时间：" + DateTime.Now + "-->";
                        srFile.WriteLine(text);
                        srFile.Close();
                        srFile.Dispose();
                        return true;
                    }
                }
                logs = DateTime.Now + "\r\n事件名称：生成静态页写文件函数\r\n结果:\r\n生成失败，错误信息为：请求路径或生成文件名称为空\r\n请求路径为：" + rewriteUrl + "\r\n生成文件名称为：" + rewriteFileName + "\r\n";
                logs.AddLogFiles("/Logs/CreateFile/" + DateTime.Now.FormatDateToString("yyyyMMdd") + ".log", 1);
                return false;
            }
            catch (Exception ex)
            {
                logs = DateTime.Now + "\r\n事件名称：生成静态页写文件函数\r\n结果:\r\n生成失败，异常信息为：\r\n" + ex.ToString();
                logs.AddLogFiles("/Logs/CreateFile/" + DateTime.Now.FormatDateToString("yyyyMMdd") + ".log", 1);
                return false;
            }
        }
    }


    public class StaticFileOpreate
    {

        private string docName = "";
        public StaticFileOpreate()
        {
            docName = System.AppDomain.CurrentDomain.BaseDirectory + "/Configs/StaticFile.xml";//配置文件路径 
        }


        /// <summary> 
        /// 加载Config文件 
        /// </summary> 
        /// <param name="path"></param> 
        /// <returns></returns> 
        public XDocument Load()
        {
            FileInfo file = new FileInfo(docName);
            file.IsReadOnly = false;
            return XDocument.Load(docName);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="fileName"></param>
        /// <param name="requestFile"></param>
        /// <param name="responeFile"></param>
        /// <returns>-2：异常错误，0：已存在，1：添加成功</returns>
        public int Add(string fileId, string fileName, string requestFile, string responeFile)
        {
            XDocument xDoc = Load();
            try
            {
                var query = from p in xDoc.Descendants("FileInfo") where p.Element("FileId").Value == fileId select p;
                if (query.Count() > 0)
                {
                    return 0;
                }
                xDoc.Element("FileList").Add(new XElement("FileInfo",
              new XElement("FileId", fileId),
              new XElement("FileName", fileName),
              new XElement("RequestFile", requestFile),
              new XElement("ResponeFile", responeFile)));
                xDoc.Save(docName);
                return 1;
            }
            catch (Exception ex)
            {
                return -2;

            }

        }


        /// <summary> 
        /// 删除 
        /// </summary> 
        /// <param name="fileId">编号</param>    
        /// <returns>-2：异常错误，0：不存在，1：成功</returns> 
        public int Remove(string fileId)
        {
            try
            {
                XDocument xDoc = Load();
                var query = from p in xDoc.Descendants("FileInfo")
                            where p.Element("FileId").Value == fileId
                            select p;
                if (query.Count() <= 0)
                {
                    return 0;
                }
                else
                {
                    query.Remove();
                    xDoc.Save(docName);
                    return 1;
                }

            }
            catch (Exception ex)
            {
                return -2;

            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="fileName"></param>
        /// <param name="requestFile"></param>
        /// <param name="responeFile"></param>
        /// <returns>-2：异常错误，0：已存在，1：添加成功</returns>
        public int Modify(string fileId, string fileName, string requestFile, string responeFile)
        {
            try
            {
                XDocument xDoc = Load();
                var query = from p in xDoc.Descendants("FileInfo")
                            where p.Element("FileId").Value == fileId
                            select p;
                var currentElement = query.FirstOrDefault();
                if (currentElement != null)
                {
                    currentElement.Element("FileName").Value = fileName;
                    currentElement.Element("RequesFile").Value = requestFile;
                    currentElement.Element("ResponeFile").Value = responeFile;
                    xDoc.Save(docName);
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                return -2;
            }

        }

        /// <summary>
        /// 获取单个模板
        /// </summary>
        /// <param name="templateName">模板名称</param>     
        /// <returns></returns>
        public FileInfoModel GetFileInfo(string fileId)
        {
            XDocument xDoc = Load();
            var query = from p in xDoc.Descendants("FileInfo")
                        where p.Element("FileId").Value == fileId
                        select new FileInfoModel
                        {
                            FileId = p.Element("FileId").Value,
                            FileName = p.Element("FileName").Value,
                            RequestFile = p.Element("RequestFile").Value,
                            ResponeFile = p.Element("ResponeFile").Value
                        };

            return query.FirstOrDefault();
        }

        /// <summary>
        /// 获取所有模板
        /// </summary>
        /// <returns></returns>
        public IList<FileInfoModel> GetFileList()
        {
            XDocument xDoc = Load();
            var query = from p in xDoc.Descendants("FileInfo")
                        select new FileInfoModel
                        {
                            FileId = p.Element("FileId").Value,
                            FileName = p.Element("FileName").Value,
                            RequestFile = p.Element("RequestFile").Value,
                            ResponeFile = p.Element("ResponeFile").Value
                        };

            return query.ToList();
        }
    }

    public class FileInfoModel
    {
        private string fileId = string.Empty;
        /// <summary>
        /// 文件Id号
        /// </summary>
        public string FileId
        {
            get { return fileId; }
            set { fileId = value; }
        }
        private string fileName = string.Empty;
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
        private string requestFile = string.Empty;
        /// <summary>
        /// 请求页面绝对路径
        /// </summary>
        public string RequestFile
        {
            get { return requestFile; }
            set { requestFile = value; }
        }
        private string responeFile = string.Empty;
        /// <summary>
        /// 生成静态页相对路径，由"/"开头
        /// </summary>
        public string ResponeFile
        {
            get { return responeFile; }
            set { responeFile = value; }
        }
    }
}
